package com.siro.auth.base.config.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 *
 * @author starsea
 * @date 2022-12-15 19:35
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {

    private static final Logger log = LoggerFactory.getLogger(ThreadPoolConfig.class);

    @Autowired
    private ThreadPoolParamsConfig threadPoolParamsConfig;

    @Override
    @Bean("taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolParamsConfig.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolParamsConfig.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolParamsConfig.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolParamsConfig.getKeepAliveSeconds());
        executor.setThreadNamePrefix("authority-manage-thread-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex,method,params) -> {
          log.error("异常信息：{}",ex.getMessage());
          log.error("exception method:{}",method.getName());
        };
    }
}
